import React, {Component, useContext, useState} from 'react';
import {
    View,
    Alert,
    Button,
    Text,
    TextInput,
    ActivityIndicator,
    ImageBackground,
    Keyboard,
    TouchableOpacity, Animated, Dimensions, Platform
} from 'react-native';

import WebView from 'react-native-webview';
import pool_find from '../assets/Pool/pool_find.png';
import {Icon, Input, ListItem} from "react-native-elements";
import image_left  from '../assets/explore/left.png';
import image_right  from '../assets/explore/right.png';
import image_refresh  from '../assets/explore/refresh.png';
import image_return  from '../assets/explore/return.png';
import LocaleContext from "../libs/locale";
import {tokenTransfer, tokenTransfer192, transfer} from "../libs/nodes";
import {addTx} from "../libs/pendingTxs";
import {formartMoney} from "../libs/helpers";
import {checkPassword} from "../libs/wallet";
import {constansts} from "../libs/constansts";
import {keyPairFromSeed, sign as keyPairSign} from "../libs/keyPair";
import CryptoJS from "crypto-js";


type Props = {};
type State = {};

var url = '';

function upgradeURL(uri:string) {
    const isURL = uri.split(' ').length === 1 && uri.includes('.');
    if (isURL) {
        if (!uri.startsWith('http')) {
            return 'https://' + uri;
        }
        return uri;
    }return '';
}

export default class WebComponentDM extends Component<Props, State> {
    [x: string]: any;
    // state = {site:'site'};
    state = {
        currentURL: "https://testnet.smartx.one/browser",
        preURL:url,
        showTranInfo:false,
        giveAuth:false,
        inputPassword: false,
        pwdVisible:false,
        pwdError:"",
        pwd:"",
        minGet:"",
        transfering:false,
        tranInfo:"",
        tranType:"",
        tokenNum:1,
        tokenName:"SAT",
    }


    constructor(props: Props | Readonly<Props>) {
        super(props);
        this.webView = React.createRef();
        if((this.props as any).url) {
            const newURL = upgradeURL((this.props as any).url);
            this.state.currentURL = newURL;
            this.state.preURL = newURL;
            // console.log(this.state.currentURL)
        }
        setInterval(()=>{this.setState({transfering:false});
            console.log("this.state.transfering="+this.state.transfering)},20000)

    }


    // andoirFunction = (callback) => {
    //
    //     if (window.WebViewJavascriptBridge) {
    //         callback(window.WebViewJavascriptBridge);
    //     } else {
    //         document.addEventListener('WebViewJavascriptBridgeReady', function () {
    //             callback(window.WebViewJavascriptBridge);
    //         }, false)
    //     }
    // }
    //
    // /**
    //  * IOS 与 IOS 交互时，使用这个函数即可，别的操作都不需要执行
    //  * @param {*} callback
    //  */
    // iosFuntion = (callback) => {
    //     if (window.WebViewJavascriptBridge) { return callback(window.WebViewJavascriptBridge) }
    //     if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback) }
    //     window.WVJBCallbacks = [callback];
    //     var WVJBIframe = document.createElement('iframe');
    //     WVJBIframe.style.display = 'none';
    //     WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    //     document.documentElement.appendChild(WVJBIframe);
    //     setTimeout(function(){
    //         document.documentElement.removeChild(WVJBIframe);
    //     }, 0);
    // }



    sendTran = async ()=>{
        if(this.state.transfering)
        {
            Alert.alert('', "转账中");
            return;
        }
        this.setState({transfering:true});
        if (!checkPassword((this.props as any).wallet, this.state.pwd)) {
            this.setState({pwdError:(this.props as any).locale?._('Import.passwordError')});
            return;
        }

        var wallet = (this.props as any).wallet;
        var tx;
        if(this.state.tranType=="transfer"){
            tx= await transfer(wallet.seed, wallet.address, (this.state.tranInfo as any).receiver, (this.state.tranInfo as any).amount, (this.state.tranInfo as any).remarks);
        }
        else{
            tx = await tokenTransfer192(wallet.seed, wallet.address, (this.state.tranInfo as any).receiver, (this.state.tranInfo as any).data,'',"");
        }
        if (tx.reason != 1) {
            console.log("false reason=" + tx.reason + "     " + (this.state.tranInfo as any).amount);
            Alert.alert((tx.reason as any).toString(), (this.props as any).locale._('Assets.send.sendFail'));
            return ;
        } else {
            await addTx(tx);
            Alert.alert('', (this.props as any).locale._('Assets.send.sendSuccess'), [{
                text: (this.props as any).locale?._('Assets.send.OK'), onPress: () => {
                }
            }]);//TODO 交易已广播 2021-03-06
        }
        this.state.tranInfo = "";
        this.setState({inputPassword:false});
        var res = {hash:tx.hash,checkInfo:"sendTran"};
        this.webView.current.postMessage(JSON.stringify(res));
    }


    sendInfoToMiner= async (info: string) => {
        if (info == "needAddress") {
            console.log("info="+info);
            console.log((this.props as any).wallet.address)
            if ((this.props as any).wallet.address) {

                Alert.alert('', (this.props as any).locale?._('authorized'), [{
                    text: (this.props as any).locale?._('cancel'),
                    onPress: () => {
                        (this.props as any).navigation.goBack();
                    },
                    style: "cancel"
                },
                    {
                        text: (this.props as any).locale?._('ok'),
                        onPress: () => {
                            this.state.giveAuth=true;
                            var res = {address:(this.props as any).wallet.address,checkInfo:"getAuth"};
                            this.webView.current.postMessage(JSON.stringify(res));
                        }
                    }]);
                // (this.props as any).navigation.goBack();
                //加一个窗口确认时候发送地址或者取消返回
                // this.webView.current.postMessage((this.props as any).wallet.address);
                // Alert.alert("发送地址:"+(this.props as any).wallet.address);
            }
        }
        else if (info.indexOf("needTranSmartX") != -1) {
            if(!this.state.giveAuth)
            {
                this.webView.current.postMessage("未获取授权")
                return ;
            }
            try {
                //加一个窗口确认是否发送交易。然后上面放置交易信息，大概跟交易的时候差不多
                var tranInfoData = JSON.parse(info);
                console.log("tranInfo.checkInfo=" + tranInfoData.checkInfo)
                this.setState({tranInfo:tranInfoData});
                this.setState({tranType:"transfer"});
                this.setState({tokenName:"SAT"});
                this.setState({tokenNum:1});
                this.setState({showTranInfo:true})
                // tokenName:"SAT",


            } catch (e) {
                Alert.alert("", "错误信息：" + e);
            }
            //后面用来进行交易
        }
        else if(info.indexOf("needTokenTranSmartX") != -1){
            if(!this.state.giveAuth)
            {
                this.webView.current.postMessage("未获取授权")
                return ;
            }
            try {
                //加一个窗口确认是否发送交易。然后上面放置交易信息，大概跟交易的时候差不多
                var tranInfoData = JSON.parse(info);
                console.log("tranInfo.checkInfo=" + tranInfoData.checkInfo)
                this.setState({tranInfo:tranInfoData});
                this.setState({tranType:"contract"});
                this.setState({tokenNum:tranInfoData.tokenNum});
                this.setState({tokenName:tranInfoData.token1Name});
                this.setState({minGet:tranInfoData.minGet});
                this.setState({showTranInfo:true});
                // await this.sendTran(tranInfo);

            } catch (e) {
                Alert.alert("", "错误信息：" + e);
            }
        }
        else if(info.indexOf("needSmartXSign"))
        {
            if(!this.state.giveAuth)
            {
                this.webView.current.postMessage("未获取授权")
                return ;
            }

            const keyPair = keyPairFromSeed((this.props as any).wallet.seed);
            const sign = keyPairSign(keyPair,CryptoJS.SHA256((this.props as any).wallet.address).toString())
            var res = {sign:sign,checkInfo:"getSign"};
            this.webView.current.postMessage(JSON.stringify(res));

        }
        else {
            Alert.alert("", "错误信息：" + info)
        }
    }

    onNavigationStateChange = (navState:any) =>{
        console.log(navState.url);
        // this.state.preURL = navState.url;
        this.setState({
            preURL:navState.url,
        })
    }

    //合约搜索
    inputOnEndEditing = (preURL:any)=>{
        if(preURL=="")
        {
            return;
        }
        try {
            // this.seachTxt = 'https://www.baidu.com';
            // if(this.seachTxt == "") return;
            // this.webView.setUrl('https://www.baidu.com');
            const newURL = upgradeURL(preURL);
            this.setState({
                currentURL: newURL,
            });

            Keyboard.dismiss();
            this.state.preURL=preURL;
            // const info = await this.webView.reload;
            // Alert.alert("","test");
        } catch (e) {
            console.log('inputOnEndEditing:', e);
        }

    };

    render() {
        const {state} = this;
        const {currentURL,preURL,showTranInfo,inputPassword,pwdVisible,pwdError,pwd,transfering} = state;
        const imageraScaling = 0.7;
        const {width,height,scale} = Dimensions.get("window");
        // const [pwdVisible, setPwdVisible] = useState(false);
        // const [pwdError, setPwdError] = useState('');
        // const [pwd, setPwd] = useState('');
        // const [transfering, setTransfering] = useState(false);

        return (
            <View style={{height: '100%', marginTop:0, overflow:'hidden'}}>
                {
                    (this.props as any).showExplore?
                        <View
                            style={{
                                width:'95%',height:48,backgroundColor:'white',marginTop:5
                                ,marginBottom:10,borderWidth:0.3,borderRadius:10,borderColor:'black'
                                ,flexDirection:'row',alignSelf:"center",
                            }}>
                            <ImageBackground
                                source={pool_find}
                                style={{ width: 15,
                                    height:15,
                                    marginLeft:20,
                                    marginRight:10,
                                    alignSelf:'center',
                                    alignItems:'center'}} />
                            <TextInput
                                underlineColorAndroid={'transparent'}
                                placeholder = {'请输入网址'}
                                value={preURL}
                                onChangeText = {
                                    (value) => {
                                        this.setState({
                                            preURL: value.trim(),
                                        });
                                    }
                                }
                                onEndEditing={()=>this.inputOnEndEditing(preURL)}
                                style={{
                                    width:"70%",
                                    marginLeft:0
                                }
                                }/>
                            <TouchableOpacity onPress={()=>this.inputOnEndEditing(preURL)}>
                                <View style={{backgroundColor:"",flex:1,flexDirection:"row",alignItems:"center"}}>
                                    <View style={{backgroundColor:"grey",marginTop:15,marginBottom:15,width:0.5,height:25,marginRight:10}} />
                                    <Text>
                                        搜索
                                    </Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        :null
                }
                <WebView
                    ref={this.webView}
                    source={{uri: currentURL,method: 'GET', headers: { 'Cache-Control':'no-cache'}}}
                    onLoadEnd={()=>{
                        console.log("currentURL="+currentURL)
                    }}
                    scalesPageToFit={true}
                    domStorageEnabled={ true }
                    javaScriptEnabled={ true }
                    automaticallyAdjustContentInsets={false}
                    onNavigationStateChange={this.onNavigationStateChange.bind(this)}
                    onMessage={(e: {nativeEvent: {data?: string}}) => {
                        // Alert.alert('接收到信息: ', e.nativeEvent.data);
                        this.sendInfoToMiner(e.nativeEvent.data as string);
                    }}
                    startInLoadingState={true}
                    mixedContentMode={"always"}
                    renderLoading={() => (
                        <ActivityIndicator
                            color='black'
                            size='large'
                            style={{flex: 1, justifyContent: 'center'}}
                        />
                    )}
                />
                {
                    (this.props as any).showBottom?
                        <View style={{marginBottom:0,height:"7%",flexDirection:"row",backgroundColor:"#F5F5F5" }}>
                            <TouchableOpacity style={{backgroundColor:"#F5F5F5",flex:1,alignItems:"center",justifyContent:"center"}} onPress={()=>this.webView.current.goBack()}>
                                <ImageBackground source={image_left} style={{width:15*imageraScaling,height:30*imageraScaling}}></ImageBackground>
                            </TouchableOpacity>
                            {/*<View style={{height:25,width:0.4,backgroundColor:"grey",alignSelf:"center"}} />*/}
                            <TouchableOpacity style={{backgroundColor:"#F5F5F5",flex:1,alignItems:"center",justifyContent:"center",paddingTop:0}} onPress={()=>this.webView.current.goForward()}>
                                <ImageBackground source={image_right} style={{width:15*imageraScaling,height:30*imageraScaling}}></ImageBackground>
                                {/*<Icon type='font-awesome-5' name="share" color={'black'} size={25}/>*/}
                            </TouchableOpacity>
                            {/*<View style={{height:25,width:0.4,backgroundColor:"grey",alignSelf:"center",paddingTop:20}} />*/}
                            <TouchableOpacity style={{backgroundColor:"#F5F5F5",flex:1,alignItems:"center",justifyContent:"center" }} onPress={()=>this.webView.current.reload()}>
                                <ImageBackground source={image_refresh} style={{width:30*imageraScaling,height:34*imageraScaling}}></ImageBackground>
                                {/*<Icon type='font-awesome-5' name="redo" color={'black'} size={25}/>*/}
                            </TouchableOpacity>
                            {/*/!*<View style={{height:25,width:0.4,backgroundColor:"grey",alignSelf:"center"}} />*!/*/}
                            <TouchableOpacity style={{backgroundColor:"#F5F5F5",flex:1,alignItems:"center",justifyContent:"center"}} onPress={()=>this.inputOnEndEditing((this.props as any).url)}>
                                <ImageBackground source={image_return} style={{width:27*imageraScaling,height:30*imageraScaling}}></ImageBackground>
                                {/*<Icon type='font-awesome-5' name="home" color={'black'} size={25}/>*/}
                            </TouchableOpacity>
                            {/*<View style={{height:25,width:0.4,backgroundColor:"grey",alignSelf:"center"}} />*/}
                            {/*<TouchableOpacity style={{backgroundColor:"#F5F5F5" ,flex:1,alignItems:"center",justifyContent:"center"}} onPress={()=>WebView.extraNativeComponentConfig()}>*/}
                            {/*    <Icon type='font-awesome-5' name="undo" color={'black'} size={25}/>*/}
                            {/*</TouchableOpacity>*/}
                        </View>:null
                }
                {
                    showTranInfo?
                        <View style={{marginTop: -height, alignItems: 'center'}}>
                            <View style={{width: '100%', height: height}}>
                                <View style={{
                                    alignItems: 'center',
                                    flex: 1,
                                    opacity: 0.5,
                                    backgroundColor: 'black'
                                }}>
                                    <TouchableOpacity style={{height: height * 0.5, width: "100%"}}
                                                      onPress={()=>{this.setState({showTranInfo:false});}}>
                                    </TouchableOpacity>
                                </View>
                                <View style={{
                                    width: "100%",
                                    backgroundColor: 'white',
                                    minHeight: 380,
                                }}>
                                    <View style={{
                                        flexDirection: 'row',
                                        paddingVertical: 20,
                                    }}>
                                        <Text style={{
                                            fontSize: 18,
                                            fontWeight: 'bold',
                                            textAlign: 'center',
                                            flex: 1
                                        }}>{(this.props as any).locale?._('Assets.send.payDetailTitle')}</Text>
                                        <TouchableOpacity
                                            style={{position: 'absolute', padding: 20}}
                                            onPress={()=>{this.setState({showTranInfo:false});}}
                                        >
                                            <Icon type='font-awesome' name='close' color='#333333FF'
                                                  size={24}/>
                                        </TouchableOpacity>
                                    </View>
                                    {/***交易金额**/}
                                    <View style={{
                                        height: 80,
                                        justifyContent: 'center',
                                        alignItems: 'center'
                                    }}>{
                                        this.state.tokenNum==1?
                                            (<Text
                                                style={{fontSize: 25, fontWeight: 'bold', textAlign: 'center'}}>
                                                -{(this.state.tranInfo as any).amount} {(this.state as any).tokenName}
                                            </Text>)
                                            :
                                            <Text
                                                style={{fontSize: 25, fontWeight: 'bold', textAlign: 'center'}}>
                                                -{(this.state.tranInfo as any).token1Amount} {(this.state.tranInfo as any).token1Name} {"\n"} -{(this.state.tranInfo as any).token2Amount} {(this.state.tranInfo as any).token2Name}
                                            </Text>
                                    }
                                        {
                                            this.state.minGet!==""?
                                                <Text
                                                    style={{fontSize: 20, fontWeight: 'bold', textAlign: 'center'}}>
                                                    minget: +{(this.state as any).minGet} {(this.state.tranInfo as any).token2Name}
                                                </Text>:null
                                        }

                                    </View>
                                    {/*<View style={ {height:1,backgroundColor:'#8a8a8a'}}/>*/}
                                    {/***收款账户**/}
                                    <ListItem bottomDivider>
                                        <Text style={{width: 100, fontSize: 18, textAlign: 'center'}}>
                                            {(this.props as any).locale?._('Assets.send.payDetailReceiver')}
                                        </Text>
                                        <ListItem.Content>
                                            <ListItem.Title>{(this.state.tranInfo as any).receiver}</ListItem.Title>
                                        </ListItem.Content>
                                    </ListItem>
                                    {/***付款账户**/}
                                    <ListItem bottomDivider>
                                        <Text style={{width: 100, fontSize: 18, textAlign: 'center'}}>
                                            {(this.props as any).locale?._('Assets.send.payDetailTitleSender')}
                                        </Text>
                                        <ListItem.Content>
                                            <ListItem.Title>{(this.props as any).wallet.address}</ListItem.Title>
                                        </ListItem.Content>
                                    </ListItem>
                                    {/***‘确定’按钮**/}
                                    <TouchableOpacity style={{
                                        width: 334,
                                        height: 40,
                                        justifyContent: 'center',
                                        backgroundColor: '#088DE8',
                                        alignItems: 'center',
                                        alignSelf: 'center' ,
                                        marginTop: 20,
                                        borderColor: '#088DE8',
                                        borderWidth: 1,
                                        borderRadius: 10
                                    }}
                                                      onPress={() => {
                                                          // this.state.showTranInfo = false;
                                                          // this.state.inputPassword = true;
                                                          this.setState({showTranInfo:false});
                                                          this.setState({inputPassword:true})
                                                      }}>
                                        <Text style={{
                                            // marginTop: 160,
                                            fontSize: 20,
                                            textAlign: 'center',
                                            color: 'white'
                                        }}>{(this.props as any).locale._('Assets.send.payDetailBtnOK')}</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                        :null
                }
                {
                    inputPassword?
                        <View style={{marginTop: -height, alignItems: 'center'}}>
                            <View style={{width: '100%', height: height}}>
                                <View style={{
                                    alignItems: 'center',
                                    flex: 1,
                                    backgroundColor: 'black',
                                    opacity: 0.5
                                }}>
                                    <TouchableOpacity style={{height: height * 0.5, width: "100%"}}
                                                      onPress={() => {this.setState({inputPassword:false})}}>
                                    </TouchableOpacity>
                                </View>
                                <View style={{
                                    backgroundColor: 'white',
                                    borderTopLeftRadius: 27,
                                    borderTopRightRadius: 27,
                                    minHeight: 280,
                                }}>
                                    <View style={{
                                        flexDirection: 'row',
                                        paddingVertical: 20,
                                    }}>
                                        <Text style={{
                                            fontSize: 18,
                                            fontWeight: 'bold',
                                            textAlign: 'center',
                                            flex: 1
                                        }}>{(this.props as any).locale?._('Import.password')}</Text>
                                        <TouchableOpacity
                                            style={{position: 'absolute', padding: 20}}
                                            onPress={() => {this.setState({inputPassword:false})}}
                                        >
                                            <Icon type='font-awesome' name='close' color='#333333FF'
                                                  size={24}/>
                                        </TouchableOpacity>
                                    </View>
                                    <Input
                                        autoFocus={true}
                                        placeholder={(this.props as any).locale?._('Assets.send.pwHint')}
                                        rightIcon={<Icon
                                            name={pwdVisible ? 'eye' : 'eye-off'}
                                            type='feather'
                                            onPress={() => this.setState({pwdVisible:!pwdVisible})}
                                        />}
                                        secureTextEntry={!pwdVisible}
                                        errorMessage={pwdError}
                                        onChangeText={value => this.setState({pwd:value})}
                                        // onFocus={()=>{setPWDfocus(true);}}
                                        // onBlur={()=>{setPWDfocus(false)}}
                                    />
                                    <View style={{flex: 1}}></View>
                                    <View style={{
                                        flexDirection: 'row',
                                        bottom: 0,
                                        marginTop: 10,
                                        marginBottom: 20,
                                        alignSelf: 'center'
                                    }}>
                                        {
                                            pwd
                                                ?
                                                <TouchableOpacity style={{
                                                    width: "96%",
                                                    height: 40,
                                                    justifyContent: 'center',
                                                    backgroundColor: '#088DE8',
                                                    alignItems: 'center',
                                                    borderColor: '#088DE8',
                                                    borderWidth: 1,
                                                    borderRadius: 10
                                                }}
                                                                  disabled={transfering}
                                                                  onPress={this.sendTran}>
                                                    <Text style={{
                                                        // marginTop: 160,
                                                        fontSize: 20,
                                                        textAlign: 'center',
                                                        color: 'white'
                                                    }}>{(this.props as any).locale._('Assets.send.payDetailBtnOK')}</Text>
                                                </TouchableOpacity>
                                                :
                                                <TouchableOpacity style={{
                                                    width: "96%",
                                                    height: 40,
                                                    justifyContent: 'center',
                                                    backgroundColor: '#C6C7CB',
                                                    alignItems: 'center',
                                                    borderColor: '#C6C7CB',
                                                    borderWidth: 1,
                                                    borderRadius: 10
                                                }} onPress={this.sendTran}>
                                                    <Text style={{
                                                        // marginTop: 160,
                                                        fontSize: 20,
                                                        textAlign: 'center',
                                                        color: 'white'
                                                    }}>{(this.props as any).locale._('Assets.send.payDetailBtnOK')}</Text>
                                                </TouchableOpacity>
                                        }
                                    </View>
                                </View>
                            </View>
                        </View>
                        :null
                }

            </View>

        );
    }
}
